<template>
  <view class="wrap">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 班级页面内容 -->
    <view class="class-container">
      <!-- 标题 -->

      <!-- 用户图标和提示 -->
      <view class="user-section" v-if="!hasJoinedClass">
        <view class="user-icon">
          <text class="icon">👥</text>
        </view>
        <view class="tip-text">您还没有加入任何班级</view>
      </view>

      <!-- 班级列表 -->
      <view class="class-list" v-if="hasJoinedClass">
        <view class="class-item" v-for="(classItem, index) in classList" :key="index"
              @click="enterClassDetail(classItem)">
          <view class="class-info">
            <view class="class-name">{{ classItem.classManagementName }}</view>
            <view class="class-teacher">教师：{{ classItem.classManagementTeacher }}</view>
          </view>
          <view class="class-arrow">
            <u-icon name="arrow-right" color="#ccc" size="28"></u-icon>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="button-section">
        <view class="action-btn join-btn" @click="joinClass">
          <text class="btn-text">加入班级</text>
        </view>
        <view class="action-btn create-btn" @click="createClass">
          <text class="btn-text">创建班级</text>
        </view>
        <view class="action-btn enter-btn" @click="createHomework">
          <text class="btn-text">创建作业</text>
        </view>
      </view>

      <!-- 班级功能介绍 -->
      <view class="feature-section">
        <view class="feature-title">班级功能介绍</view>
        <view class="feature-content">
          <text class="feature-text">班级主要用于老师布置作业，多人组团打卡或同学之间同步学习等场景。</text>
        </view>
        <view class="feature-item">
          <text class="feature-number">1</text>
          <text class="feature-desc">VIP用户才可创建班级，老师可以免费申请身份VIP</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config'
import {
  createBookClassManagement,
  getBookClassManagementById,
  updateBookClassManagement,
  createBookSchoolAssignment,
  updateBookSchoolAssignment,
  deleteBookSchoolAssignment,
  getBookClassManagementBookSchoolAssignmentList,
  submitJob,
  joinBookClassManagement, getBookClassManagementList
} from '@/api/bookSchoolAssignment'

const App = getApp()

export default {
  components: {},
  data() {
    return {
      statusBarHeight: 0,
      classList: [], // 班级列表
      hasJoinedClass: false, // 是否已加入班级
      currentClassId: null, // 当前班级ID
      currentClassDetail: null, // 当前班级详情
      assignmentList: [], // 作业列表
      userInfo: null // 用户信息
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;
    this.loadClassData();

    // 监听班级列表刷新事件
    uni.$on('refreshClassList', () => {
      this.loadClassData();
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 移除事件监听
    uni.$off('refreshClassList');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadClassData();
  },

  methods: {
    /**
     * 加载班级数据
     */
    async loadClassData() {
      try {

        this.classList = (await getBookClassManagementList()).data;
        this.hasJoinedClass = this.classList.length > 0;

        // 如果有班级，获取第一个班级的详细信息
        if (this.hasJoinedClass && this.classList.length > 0) {
          this.currentClassId = this.classList[0].id;
          await this.loadClassDetail(this.currentClassId);
        }
      } catch (error) {
        console.error('加载班级数据失败:', error);
        uni.showToast({
          title: '加载班级数据失败',
          icon: 'none'
        });
      }
    },

    /**
     * 加入班级
     */
    joinClass() {
      uni.navigateTo({
        url: '/pages/class/join'
      });
    },

    /**
     * 进入班级
     */
    enterClass() {
      uni.navigateTo({
        url: '/pages/class/detail'
      });
    },

    /**
     * 创建班级
     */
    createClass() {
      uni.navigateTo({
        url: '/pages/class/create'
      });
    },

    /**
     * 加载班级详情
     */
    async loadClassDetail(classId) {
      try {
        const result = await getBookClassManagementById(classId);
        this.currentClassDetail = result.data;
        this.assignmentList = result.data.bookSchoolAssignmentSaveRespVOList || [];
      } catch (error) {
        console.error('加载班级详情失败:', error);
      }
    },

    /**
     * 进入班级详情
     */
    async enterClassDetail(classItem) {
      try {
        await this.loadClassDetail(classItem.id);
        // 这里可以跳转到班级详情页面，传递班级信息
        console.log(this.currentClassDetail)
        uni.navigateTo({
          url: `/pages/class/detail?classId=${this.currentClassDetail.id}&className=${this.currentClassDetail.classManagementName}&memberCount=${this.currentClassDetail.num}&code=${this.currentClassDetail.code}&teacher=${this.currentClassDetail.classManagementTeacher}`
        });
      } catch (error) {
        console.error('进入班级详情失败:', error);
      }
    },

    createHomework() {
      uni.navigateTo({
        url: `/pages/class/create-homework`
      });
    },

    /**
     * 创建作业
     */
    async createAssignment(assignmentData) {
      try {
        const result = await createBookSchoolAssignment(assignmentData);
        if (result.code === 200) {
          uni.showToast({
            title: '创建作业成功',
            icon: 'success'
          });
          // 重新加载班级详情
          if (this.currentClassId) {
            await this.loadClassDetail(this.currentClassId);
          }
        }
      } catch (error) {
        console.error('创建作业失败:', error);
        uni.showToast({
          title: '创建作业失败',
          icon: 'none'
        });
      }
    },

    /**
     * 更新作业
     */
    async updateAssignment(assignmentData) {
      try {
        const result = await updateBookSchoolAssignment(assignmentData);
        if (result.code === 200) {
          uni.showToast({
            title: '更新作业成功',
            icon: 'success'
          });
          // 重新加载班级详情
          if (this.currentClassId) {
            await this.loadClassDetail(this.currentClassId);
          }
        }
      } catch (error) {
        console.error('更新作业失败:', error);
        uni.showToast({
          title: '更新作业失败',
          icon: 'none'
        });
      }
    },

    /**
     * 删除作业
     */
    async deleteAssignment(assignmentId) {
      try {
        const res = await uni.showModal({
          title: '确认删除',
          content: '确定要删除这个作业吗？',
          confirmText: '删除',
          cancelText: '取消'
        });

        if (res.confirm) {
          const result = await deleteBookSchoolAssignment(assignmentId);
          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            // 重新加载班级详情
            if (this.currentClassId) {
              await this.loadClassDetail(this.currentClassId);
            }
          }
        }
      } catch (error) {
        console.error('删除作业失败:', error);
        uni.showToast({
          title: '删除作业失败',
          icon: 'none'
        });
      }
    },

    /**
     * 提交作业
     */
    async submitAssignment(bookId, classManagementId) {
      try {
        const result = await submitJob({
          bookId: bookId,
          classManagementId: classManagementId
        });
        if (result.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });
          // 重新加载班级详情
          if (this.currentClassId) {
            await this.loadClassDetail(this.currentClassId);
          }
        }
      } catch (error) {
        console.error('提交作业失败:', error);
        uni.showToast({
          title: '提交作业失败',
          icon: 'none'
        });
      }
    }
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    const app = this
    return {
      title: config.name,
      path: "/pages/index/index?" + app.$getShareUrlParams()
    }
  },

  /**
   * 分享到朋友圈
   * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
   * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
   */
  onShareTimeline() {
    const app = this
    const {page} = app
    return {
      title: config.name,
      path: "/pages/index/index?" + app.$getShareUrlParams()
    }
  }

}
</script>

<style>
.wrap {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.status-bar {
  width: 100%;
  background-color: #f5f5f5;
}

.class-container {
  padding: 0 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin: 60rpx 0 120rpx 0;
}

.user-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 120rpx;
}

.user-icon {
  width: 120rpx;
  height: 120rpx;
  background-color: #e0e0e0;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.icon {
  font-size: 60rpx;
  color: #999;
}

.tip-text {
  font-size: 28rpx;
  color: #999;
  text-align: center;
}

.button-section {
  width: 100%;
  margin-bottom: 100rpx;
}

.action-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
}

.join-btn {
  background: linear-gradient(135deg, #4FC3F7 0%, #3f8ef7 100%);
}

.enter-btn {
  background: linear-gradient(135deg, #4FC3F7 0%, #3f8ef7 100%);
}

.create-btn {
  background: linear-gradient(135deg, #4FC3F7 0%, #3f8ef7 100%);
}

.btn-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.feature-section {
  width: 100%;
  padding: 0 20rpx;
}

.feature-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.feature-content {
  margin-bottom: 30rpx;
}

.feature-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.feature-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.feature-number {
  font-size: 28rpx;
  color: #4FC3F7;
  font-weight: bold;
  margin-right: 16rpx;
  margin-top: 4rpx;
}

.feature-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  flex: 1;
}

/* 班级列表样式 */
.class-list {
  width: 100%;
  margin-bottom: 60rpx;
}

.class-item {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.class-info {
  flex: 1;
}

.class-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.class-teacher {
  font-size: 26rpx;
  color: #666;
}

.class-arrow {
  font-size: 32rpx;
  color: #ccc;
  margin-left: 20rpx;
}
</style>
